<template>
  <div class="h-full">
    <div class="flex justify-center items-center h-full">
      <div class="text-white" style="width: 650px; padding: 20px; border: 1px solid #888">
        <div class="text-2xl text-center mb-5 font-bold">
          {{ !isRegister ? "用户登录" : "新用户注册" }}
        </div>

        <NForm>
          <NFormItem label="用户名" path="name">
            <NInput placeholder="输入用户名" v-model:value="formValue.username" />
          </NFormItem>
          <NFormItem label="密码" path="password">
            <NInput
              placeholder="输入密码"
              v-model:value="formValue.password"
              type="password"
            />
          </NFormItem>

          <block v-if="isRegister">
            <NFormItem label="确认密码" path="password">
              <NInput placeholder="确认密码" v-model:value="formValue.password2" />
            </NFormItem>
            <NFormItem label="邮箱" path="password">
              <NInput placeholder="邮箱" v-model:value="formValue.email" />
            </NFormItem>
            <NFormItem label="验证码" path="password">
              <NInputGroup>
                <NInput placeholder="验证码" v-model:value="formValue.verification_code" />
                <NButton type="primary" ghost @click="sendVerificationCode" :disabled="openCountdown">
                  
                  <NCountdown v-if="openCountdown" :duration="60000" :active="openCountdown" @finish="countdownFinish" :render="({seconds})=> `${String(seconds).padStart(2, '0')}后再获取`"/>
                  <span v-else>获取验证码</span>
                  
                </NButton>
              </NInputGroup>
            </NFormItem>

            <NFormItem label="邀请码" path="aff_code">
              <NInput placeholder="邀请码" v-model:value="formValue.aff_code" disabled />
            </NFormItem>
          </block>

          <NCheckbox class="mb-5" v-model:checked="isAgree"
            >我已同意并阅读<NButton
              text
              tag="a"
              href="/#/privacyPolicy"
              target="_blank"
              type="primary"
              >《用户隐私协议》</NButton
            >和<NButton
              text
              tag="a"
              href="/#/privacyPolicy"
              target="_blank"
              type="primary"
              >《服务条款》</NButton
            ></NCheckbox
          >
          <NButton
            style="width: 100%"
            size="large"
            @click="toLogin"
            v-if="!isRegister"
            :loading="loading"
          >
            登录
          </NButton>
          <NButton style="width: 100%" size="large" @click="toRegister" v-else>
            注册
          </NButton>
        </NForm>
        <div class="flex justify-between mt-2">
          <span v-if="!isRegister">
            没有账号请先
            <n-button type="primary" text @click="isRegister = true"> 注册账号 </n-button>
          </span>
          <span v-else>
            已有账户？
            <n-button type="primary" text @click="isRegister = false">点击登录 </n-button>
          </span>
          <!-- <n-button type="primary" text> 忘记密码 </n-button> -->
        </div>

        <NDivider>第三方登录</NDivider>
        <div class="flex justify-center">
          <!-- <NButton @click="showModal = true">github</NButton> -->
          <NButton @click="showModal = true">微信公众号</NButton>
          <!-- <NButton @click="showModal = true">微信登录</NButton> -->
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <NModal
      title="微信扫码登录"
      v-model:show="showModal"
      preset="card"
      style="width: 600px"
    >
      <div style="display: flex; justify-content: space-between; margin-top: 20">
        <img
          :src="wechatQrcode"
          style="border: 1px solid #eee; width: 120px; height: 120px; margin: 10px auto"
        />
      </div>
      <div style="text-align: center">
        <p>微信扫码关注公众号，输入「验证码」获取验证码（三分钟内有效）</p>
      </div>
      <NForm size="large">
        <NFormItem label="验证码" path="">
          <NInput placeholder="验证码" />
        </NFormItem>
      </NForm>
    </NModal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from "vue";
import {
  NInputGroup,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NDivider,
  NModal,
  NCheckbox,
  useMessage,
  NCountdown
} from "naive-ui";
import { useRoute, useRouter } from "vue-router";
import { setCookie } from "@/utils/cookie";
import { useUserStore } from "@/store";

import { login, fetchRegister, fetchSendEmailVerify } from "@/api/index.ts";

const message = useMessage();
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const showModal = ref(false);
const isRegister = ref(false);
const isAgree = ref(false);
const loading = ref(false);
const formValue = reactive({
  username: "",
  password: "",
  password2: "",
  email: "",
  verification_code: "",
  aff_code: route.query.aff_code || "",
});
const wechatQrcode = ref('');

const toLogin = async () => {
  if (formValue.username == "" || formValue.password == "") {
    message.error("用户名密码为空");
    return;
  }
  if (!isAgree.value) {
    message.error("请勾选并阅读用户隐私协议");
    return;
  }
  loading.value = true;
  try {
    const res = await login({
      username: formValue.username,
      password: formValue.password,
    });
    setCookie("NewApiUser", res.data.id);
    userStore.updateUserInfo(res.data);
    router.push("/");
  } catch (error) {
    loading.value = false;
    message.error("登陆错误");
  }
};

const openCountdown = ref(false)
// 获取验证码
const sendVerificationCode = async () => {
  if(!formValue.email) return;
  openCountdown.value = true;
  try {
    await fetchSendEmailVerify({email: formValue.email});
    message.success('发送成功')
  } catch (error) {
    message.error(error.message)
    openCountdown.value = false;
  }
}
const countdownFinish = ()=>{
  openCountdown.value = false
}

// 注册
const toRegister = async () => {
  if (formValue.username == "" || formValue.password == "" || formValue.password2 == "" || formValue.email == "" || formValue.verification_code == "") {
    message.error("请完整填写信息");
    return;
  }
  if (!isAgree.value) {
    message.error("请勾选并阅读用户隐私协议");
    return;
  }
  try {
    await fetchRegister(formValue);
  } catch (error) {
    message.error(error.message)
  }
};



</script>
